package com.qianniu.napi.admin.web;

import akka.actor.ActorRef;
import akka.actor.Props;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.FantimeType;
import com.qianniu.napi.admin.entity.penum.Qfxtype;
import com.qianniu.napi.admin.entity.penum.Qgettype;
import com.qianniu.napi.admin.entity.penum.Utype;
import com.qianniu.napi.admin.mapper.CouponTplMapper;
import com.qianniu.napi.admin.mapper.CouponTplShareMapper;
import com.qianniu.napi.admin.mapper.CoupontplMemberMapper;
import com.qianniu.napi.admin.mapper.LeagueMemberMapper;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.admin.service.akka.AkkaServer;
import com.qianniu.napi.admin.service.akka.OrderActor;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.DateUtil;
import com.qianniu.napi.common.util.ObjectUtil;
import com.qianniu.napi.common.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * <p>
 * </p>
 *
 * @author chenxuebin
 * @since 2018-07-07
 */
@RestController
public class CouponController {

    private static final Logger logger = LoggerFactory.getLogger(CouponController.class);

    @Autowired
    private ICouponService couponService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private ICouponTplService couponTplService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private CouponTplMapper couponTplMapper;
    @Autowired
    private LeagueMemberMapper leagueMemberMapper;
    @Autowired
    private CouponTplShareMapper couponTplShareMapper;
    @Autowired
    private CoupontplMemberMapper coupontplMemberMapper;

    @RequestMapping("/api/coupon/list")
    @ResponseBody
    public JsonDO list(@RequestParam(value = "ctype", required = false) int ctype,
                       @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                       @RequestParam(value = "pageSize", required = false) Integer pageSize,
                       @RequestParam(value = "stat", required = false) Integer stat,
                       @RequestParam(value = "gid", required = false) Long gid) {
        JsonDO json = new JsonDO();
        if (pageIndex == null) pageIndex = 1;
        if (pageSize == null) pageSize = 10;
        Page page = new Page(pageIndex, pageSize);
        Map<String, Object> map = new HashMap<String, Object>();
        Wrapper<Coupon> entity = new EntityWrapper<Coupon>()
                .eq("uid", ObjectUtil.getUid()).eq("state", 1).lt("type", 10);

        if (ctype == 0) {
            entity.ne("is_used", 1).ne("is_outdate", 1);
        } else if (ctype == 1) {
            entity.eq("is_used", 1);
        } else if (ctype == 2) {
            entity.eq("is_outdate", 1);
        }
        if (gid != null && gid > 0) {

        } else {
            page = couponService.selectPage(page, entity);
            List<Coupon> list = page.getRecords();
            for (Coupon item : list) {
                CouponTpl tpl = couponTplService.selectById(item.getTplid());
                item.setUse(tpl.getUse());
                item.setTotal(tpl.getTotal());
                item.setUsed(tpl.getUsed());
                item.setExpire(tpl.getExpire());
            }
            map.put("coupons", page.getRecords());
        }

        if (stat != null && stat == 1) {
            Map<String, Object> statMap = couponService.selectMap(new EntityWrapper<Coupon>()
                    .setSqlSelect("sum(is_unused) unUseTotal,sum(is_used) usedTotal,sum(is_outdate) outdated ")
                    .eq("uid", ObjectUtil.getUid()).lt("type", 10));

            map.put("usedTotal", statMap == null || statMap.get("usedTotal") == null ? 0 : statMap.get("usedTotal"));
            map.put("outdated", statMap == null || statMap.get("outdated") == null ? 0 : statMap.get("outdated"));

            //可使用的
            Map<String, Object> unUseMap = couponService.selectMap(new EntityWrapper<Coupon>()
                    .setSqlSelect(" sum(is_unused) unUseTotal")
                    .eq("uid", ObjectUtil.getUid()).lt("type", 10)
                    .ne("is_used", 1).ne("is_outdate", 1));

            map.put("unUseTotal", unUseMap == null || unUseMap.get("unUseTotal") == null ? 0 : unUseMap.get("unUseTotal"));
        }

        logger.debug(">>>coupon/list map=" + JSON.toJSONString(map));
        json.setData(map);
        return json;
    }

    @RequestMapping("/api/coupon/lquser")
    @ResponseBody
    public Jinfo list(@RequestParam(value = "tplid", required = true) Long tplid,
                      @RequestParam(value = "quanid", required = false) Long quanid,
                      @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                      @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        Jinfo json = new Jinfo();
        if (pageSize == null || pageSize <= 0) pageSize = 50;
        if (pageIndex == null || pageIndex <= 0) pageIndex = 1;
        Page page = new Page(pageIndex, pageSize);
        page = couponService.selectPage(page, new EntityWrapper<Coupon>()
                .eq("tplid", tplid).orderBy("id", false));
        List<Coupon> list = page.getRecords();
        if (list == null || list.size() == 0) return json;

        List<Long> uids = new ArrayList<Long>();
        for (Coupon item : list) {
            uids.add(item.getUid());
        }
        List<User> users = userService.selectList(new EntityWrapper<User>().setSqlSelect("nick_name nickName,avatar_pic avatarPic").in("id", uids));
        json.setInfo(users);

        if (quanid == null && ObjectUtil.getUid() != null) {
            Coupon Coupon = couponService.selectOne(new EntityWrapper<Coupon>()
                    .eq("is_outdate", 0)
                    .eq("is_used", 0)
                    .eq("state", 1)
                    .eq("tplid", tplid)
                    .eq("uid", ObjectUtil.getUid()));
            json.setExtra(Coupon);
        }
        return json;
    }

    //商家优惠买单可用优惠券列表接口
    @RequestMapping("/api/coupon/sulist")
    @ResponseBody
    public Jinfo sulist(@RequestParam(value = "sid", required = false) Long sid,
                        @RequestParam(value = "qid", required = false) Long qid) {
        Jinfo info = new Jinfo();
        logger.debug("================================0 sid=" + sid);
        logger.debug("================================0 qid=" + qid);
        if (sid == null && qid == null) {
            info.setCode(1);
            info.setMsg("param error");
            return info;
        }
        logger.debug("================================1 sid=" + sid);
        logger.debug("================================1 qid=" + qid);
        Coupon coupon = null;
        if (sid == null) {
            coupon = couponService.selectById(qid);
            if (coupon == null || coupon.getSid() == null) {
                info.setCode(1);
                info.setMsg("param qid error");
                return info;
            }
            sid = coupon.getSid();
        } else {
            if (qid != null) coupon = couponService.selectById(qid);
        }

        Long uid = ObjectUtil.getUid();
        if (uid == null) {
            info.setCode(1);
            info.setMsg("param uid error");
            return info;
        }

        Wrapper<Coupon> entity = new EntityWrapper<Coupon>().setSqlSelect("id,name,type,cost,usemin,sname")
                .eq("sid", sid).eq("uid", uid)
                .eq("is_unused", 1).eq("is_outdate", 0)
                .eq("state", 1).le("type", 3).orderBy("id");

        if (qid != null) entity.ne("id", qid);
        List<Coupon> list = new ArrayList<Coupon>();
        if (coupon != null) list.add(coupon);
        list.addAll(couponService.selectList(entity));
        List<String> names = new ArrayList<String>();
        for (Coupon item : list) {
            names.add(item.getName());
        }

        info.setInfo(list);
        if (list.size() > 0) info.setData(list.get(0).getSname());
        else {
            Store store = storeService.selectById(sid);
            if (store != null) info.setData(store.getName());
        }
        info.setExtra(names);

        return info;
    }

    @RequestMapping("/api/coupon/suitProduct")
    @ResponseBody
    public Jinfo suitProduct(@RequestParam(value = "cid", required = false) long cid,
                             @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                             @RequestParam(value = "pageSize", required = false) Integer pageSize,
                             HttpServletRequest req) {
        Jinfo json = new Jinfo();
        Coupon coupon = couponService.selectById(cid);

//      goodsService  **********   逻辑待完善  **********

        Wrapper<Goods> entity = new EntityWrapper<Goods>()
                .setSqlSelect("id,name, pic, price")
                .eq("mid", ObjectUtil.getMid());
        List<Goods> list = goodsService.selectList(entity);
        json.setInfo(list);
        return json;
    }

    @RequestMapping("/api/coupon/avaible22")
    @ResponseBody
    public JsonDO avaibleCoupon(@RequestParam(value = "gid", required = false) long gid,
                                @RequestParam(value = "cid", required = false) long cid,
                                HttpServletRequest req) {
        JsonDO json = new JsonDO();

//      goodsService  **********   逻辑待完善  **********

        // 未使用的优惠券
        Wrapper<Goods> entity = new EntityWrapper<Goods>()
                .setSqlSelect("id,name, pic, price")
                .eq("uid", ObjectUtil.getUid())
                .eq("used", 0)
                .eq("outdate", 0)
                .eq("mid", ObjectUtil.getMid());
        List<Goods> list = goodsService.selectList(entity);
        json.setData(list);
        return json;
    }

    @RequestMapping("/api/coupon/query")
    @ResponseBody
    public Jinfo query(@RequestParam(value = "cno", required = false) String cno) {
        Jinfo jinfo = new Jinfo();
        Wrapper<Coupon> entity = new EntityWrapper<Coupon>().eq("cno", cno);
        Coupon coupon = couponService.selectOne(entity);

        if (coupon != null) jinfo.setInfo(coupon);
        else jinfo.setCode(4);
        return jinfo;
    }

    @RequestMapping("/api/coupon/linquan")
    @ResponseBody
    public Jinfo linquan(@RequestParam(value = "tplid", required = false) Long tplid) {
        Jinfo jinfo = new Jinfo();

        Coupon coupon = new Coupon();
        coupon.setTplid(Long.valueOf(tplid));
        CouponTpl ctpl = couponTplService.selectById(tplid);
        // 不能重复领取
        if (ctpl == null || ctpl.getIsRepeat() != 1) {
            Coupon one = couponService.selectOne(new EntityWrapper<Coupon>().eq("tplid", tplid).eq("uid", ObjectUtil.getUid()));
            if (one != null) {
                jinfo.setCode(1);
                jinfo.setInfo("该优惠券不能重复领");
                return jinfo;
            }
        }

        coupon.setName(ctpl.getName());
        coupon.setType(ctpl.getType());
        coupon.setCno(StringUtil.getQuanCode(ObjectUtil.getMid()).toUpperCase());

        coupon.setIsForever(ctpl.getIsForever());
        if (ctpl.getIsForever() != 1) {
            if (ctpl.getValidType() == 1) {
                // 领取生效
                coupon.setStarttime(DateUtil.getToday());
                coupon.setEndtime(DateUtil.toDateString(DateUtil.addDay(new Date(), ctpl.getExpire()), "yyyy-MM-dd"));
                logger.info("======coupon.getEndtime=" + coupon.getEndtime());
            } else {
                // 固定日期生效
                coupon.setStarttime(ctpl.getStarttime());
                coupon.setEndtime(ctpl.getEndtime());
            }
        }
        coupon.setCost(ctpl.getCost());
        coupon.setUsemin(ctpl.getUsemin());

        coupon.setMid(ObjectUtil.getMid());
        coupon.setMpid(ObjectUtil.getMpid());
        coupon.setUid(ObjectUtil.getUid());

        coupon.setState(1);
        coupon.setIsUsed(0);
        coupon.setIsOutdate(0);
        coupon.setIsUnused(1);
        coupon.setOriginType(Qgettype.ziling.getVal());//领券来源@1：领取；2：分享；3：赠送&
        coupon.setCreatetime(new Date());//领券来源@1：领取；2：分享；3：赠送&

        coupon.insert();
        ctpl.setUse(ctpl.getUse() + 1);
        ctpl.insertOrUpdate();

        return jinfo;
    }

    //领取首页券，一次性领取全部
    //首页场景(独立版小程序首页领取优惠券)
    @RequestMapping("/api/coupon/linsyquan")
    @ResponseBody
    public Jinfo linsyquan() {
        Jinfo jinfo = new Jinfo();
        Long uid = ObjectUtil.getUid();
        if (uid == null) {
            jinfo.setCode(1);
            jinfo.setInfo("请授权登录之后再领取");
            return jinfo;
        }

        List<CouponTpl> ctpls = couponTplService.selectList(new EntityWrapper<CouponTpl>()
                .eq("is_home", 1).eq("mpid", ObjectUtil.getMpid()));

        for (CouponTpl ctpl : ctpls) {
            logger.info("================linsyquan coupon.getId=" + ctpl.getId());
            // 首页券默认不能重复领取
            int cout = couponService.selectCount(new EntityWrapper<Coupon>().eq("tplid", ctpl.getId())
                    .eq("uid", uid));
            if (cout > 0) continue;

            Coupon coupon = new Coupon();
            coupon.setTplid(Long.valueOf(ctpl.getId()));
            coupon.setName(ctpl.getName());
            coupon.setType(ctpl.getType());
            coupon.setCno(StringUtil.getQuanCode(ObjectUtil.getMid()).toUpperCase());

            coupon.setIsForever(ctpl.getIsForever());
            if (ctpl.getIsForever() != 1) {
                if (ctpl.getValidType() == 1) {
                    // 领取生效
                    coupon.setStarttime(DateUtil.getToday());
                    coupon.setEndtime(DateUtil.toDateString(DateUtil.addDay(new Date(), ctpl.getExpire()), "yyyy-MM-dd"));
                } else {
                    // 固定日期生效
                    coupon.setStarttime(ctpl.getStarttime());
                    coupon.setEndtime(ctpl.getEndtime());
                }
            }
            coupon.setCost(ctpl.getCost());
            coupon.setUsemin(ctpl.getUsemin());

            coupon.setMid(ObjectUtil.getMid());
            coupon.setMpid(ObjectUtil.getMpid());
            coupon.setUid(uid);
            coupon.setSid(ObjectUtil.getSid());

            coupon.setState(1);
            coupon.setIsUsed(0);
            coupon.setIsOutdate(0);
            coupon.setIsUnused(1);
            coupon.setOriginType(Qgettype.ziling.getVal());//领券来源@1：领取；2：分享；3：赠送&
            coupon.setCreatetime(new Date());//领券来源@1：领取；2：分享；3：赠送&

            coupon.insert();
            ctpl.setUse(ctpl.getUse() + 1);
            ctpl.setModifytime(new Date());
            ctpl.setModifier(uid);
            ctpl.insertOrUpdate();
        }

        return jinfo;
    }

    @RequestMapping("/api/coupon/avaible")
    @ResponseBody
    public Jinfo canuseYouhui(@RequestParam(value = "gid", required = false) String gid,
                              @RequestParam(value = "cid", required = false) String cid,
                              @RequestParam(value = "price", required = false) float price,
                              HttpServletRequest req) {
        Jinfo json = new Jinfo();

//      goodsService  **********   逻辑待完善  **********
        Long uid = ObjectUtil.getUid();
        long mpid = ObjectUtil.getMpid();
        if (uid == null) {
            json.setCode(1);
            json.setMsg("非法请求");
            return json;
        }

        List<Goods> goods = goodsService.selectBatchIds(Arrays.asList(gid.split(",")));
        BigDecimal total = new BigDecimal(0);
        if (goods.size() == 0) {
            json.setCode(1);
            json.setMsg("参数有误");
            return json;
        }
//        if(goods.getIsCoupon()!=1){
//            // 此商品不支持券
//            json.setInfo("");
//            return json;
//        }
        TreeSet<CouponTpl> list = new TreeSet<CouponTpl>();
        for (Goods item : goods) {
//            cids.add(item.getCid().toString());
            total.add(item.getSaleprice());
            List<CouponTpl> cs = couponTplMapper.getSuitCoupons(mpid, uid, item.getId().toString(), item.getCid().toString(), price);
            for (CouponTpl c : cs) {
                list.add(c);
            }
        }
        json.setInfo(list);
        return json;
    }

    @RequestMapping("/api/coupon/mchavaible")
    @ResponseBody
    public Jinfo mchavaible(@RequestParam(value = "gid", required = false) String gid,
                            @RequestParam(value = "sid", required = false) String sid,
                            @RequestParam(value = "cid", required = false) String cid,
                            @RequestParam(value = "ismdan", required = false) Integer ismdan,
                            @RequestParam(value = "price", required = false) float price,
                            HttpServletRequest req) {
        Jinfo json = new Jinfo();

//      goodsService  **********   逻辑待完善  **********
        Long uid = ObjectUtil.getUid();
        long mpid = ObjectUtil.getMpid();
        if (uid == null) {
            json.setCode(1);
            json.setMsg("非法请求");
            return json;
        }
        if (sid == null) {
            json.setCode(1);
            json.setMsg("参数有误");
            return json;
        }

        List<Goods> goods = goodsService.selectBatchIds(Arrays.asList(gid.split(",")));
        BigDecimal total = new BigDecimal(0);
        if (goods.size() == 0) {
            json.setCode(1);
            json.setMsg("参数有误");
            return json;
        }

        TreeSet<CouponTpl> list = new TreeSet<CouponTpl>();
        for (Goods item : goods) {
            total.add(item.getSaleprice());
            List<CouponTpl> cs = couponTplMapper.getMchSuitCoupons(mpid, uid, ismdan, item.getId().toString(), item.getCid().toString(), price);
            for (CouponTpl c : cs) {
                list.add(c);
            }
        }
        json.setInfo(list);
        return json;
    }

    @RequestMapping("/api/coupon/mechantCoupons")
    @ResponseBody
    public JsonDO mechantCoupons(@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                                 @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                 HttpServletRequest req) {
        JsonDO json = new JsonDO();

//      goodsService  **********   逻辑待完善  **********
        long mid = ObjectUtil.getMid();
        long uid = ObjectUtil.getUid();
        List<CouponTpl> list = couponTplService.getMechantCoupons(mid, uid);
        json.setData(list);
        return json;
    }

    @RequestMapping("/api/coupon/weixincoupons")
    @ResponseBody
    public JsonDO weixinoupons(@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                               @RequestParam(value = "pageSize", required = false) Integer pageSize,
                               HttpServletRequest req) {
        JsonDO json = new JsonDO();

//      goodsService  **********   逻辑待完善  **********
        Wrapper<Coupon> entity = new EntityWrapper<Coupon>()
                .eq("mid", ObjectUtil.getMid());
        List<Coupon> list = couponService.selectList(entity);
        json.setData(list);
        return json;
    }

    @RequestMapping("/api/coupon/add")
    @ResponseBody
    public JsonDO couponAdd(@Valid Coupon coupon,
                            BindingResult bindingResult, HttpServletRequest req) {
        JsonDO json = new JsonDO();
        // 字段校验
        if (bindingResult.hasErrors()) {
            logger.debug("There are errors! {}", bindingResult);
            json.setMsg("There are errors! " + bindingResult);
            json.setCode(400);
            return json;
        }
        coupon.setCreatetime(new Date());
        coupon.insert();
        return json;
    }

    @RequestMapping("/api/coupon/modify")
    @ResponseBody
    public JsonDO couponUpdate(HttpServletRequest req,
                               Coupon coupon) {
        JsonDO json = new JsonDO();
        coupon.setModifytime(new Date());
        coupon.updateById();
        return json;
    }

    @RequestMapping("/api/coupon/detail")
    @ResponseBody
    public Jinfo getCouponDetailById(@RequestParam("tplid") long tplid,
                                     @RequestParam("cno") String cno
    ) {
        Jinfo json = new Jinfo();
        Long sid = null;
        if (Strings.isNullOrEmpty(cno)) {
            CouponTpl couponTpl = couponTplService.selectOne(new EntityWrapper<CouponTpl>().eq("id", tplid));
            json.setInfo(couponTpl);
            sid = couponTpl.getSid();
        } else {
            Coupon coupon = couponService.selectOne(new EntityWrapper<Coupon>().eq("cno", cno));
            json.setInfo(coupon);
            sid = coupon.getSid();
        }
        if (sid != null) {
            Store store = storeService.selectOne(new EntityWrapper<Store>().setSqlSelect("id,name,jianchen,pic,thumb,address,latitude,longitude,phone,wxno")
                    .eq("id", sid));
            json.setExtra(store);
        }

        return json;
    }

    //被分享用户领券
    //出发分享有礼和红包券裂变
    @RequestMapping("/api/coupon/recevie")
    @ResponseBody
    public Jinfo couponRecevie(@RequestParam("tplid") long tplid,
                               @RequestParam(value = "ori", required = false) String ori,
                               @RequestParam(value = "paifa", required = false) Integer paifa,
                               @RequestParam("cno") String cno
    ) {
        Jinfo json = new Jinfo();

        CouponTpl ctpl = couponTplService.selectById(tplid);
        logger.debug("-----------------couponRecevie ctpl=" + JSON.toJSONString(ctpl));

        if (ctpl == null) {
            json.setCode(4);
            json.setMsg("该优惠券不存在");
            return json;
        }
        if (ObjectUtil.getUid() == null) {
            json.setCode(1);
            json.setMsg("请授权登录之后再操作");
            return json;
        }
        if (Strings.isNullOrEmpty(ori)) {
            json.setCode(1);
            json.setMsg("参数有误");
            return json;
        }

        int qcout = couponService.selectCount(new EntityWrapper<Coupon>().eq("tplid", tplid));

        //库存大于0时判断
        if (ctpl.getTotal() > 0 && qcout >= ctpl.getTotal()) {
            json.setCode(1);
            json.setMsg("该优惠券已被领取");
            return json;
        }
        Long uid = ObjectUtil.getUid();
        Long mpid = ObjectUtil.getMpid();
        Long zfuid = null;
        CouponTplShare couponshare = new CouponTplShare();

        //限额判断
        int hasget = couponService.selectCount(new EntityWrapper<Coupon>()
                .eq("uid", uid).eq("tplid", tplid));

        if (hasget > 0 && ctpl.getIsRepeat() != 1) {
            json.setCode(1);
            json.setMsg("该优惠券每人限领1张");
            return json;
        }
        if (ctpl.getIsRepeat() == 1 && ctpl.getRepeatNum() > 0) {
            if (hasget >= ctpl.getRepeatNum()) {
                json.setCode(1);
                json.setMsg("该优惠券每人限领" + ctpl.getRepeatNum() + "张");
                return json;
            }
        }

        //判断新客
        Wrapper<Coupon> quanEntity = new EntityWrapper<Coupon>().eq("uid", uid);
        if (ctpl.getSid() != null && ctpl.getSid() > 0) {
            quanEntity.eq("sid", ctpl.getSid());
        }
        int xkcout = couponService.selectCount(quanEntity);
        Store store = redisService.getStore(ctpl.getSid());

        Coupon coupon = couponService.selectOne(new EntityWrapper<Coupon>().eq("cno", cno));
        logger.debug("------------coupon=" + JSON.toJSONString(coupon));
        if (coupon != null) zfuid = coupon.getUid();
        logger.debug("------------coupon=" + JSON.toJSONString(coupon));

        if ((paifa != null && paifa == 1) || ctpl.getZsmode().intValue() != 1) {

            logger.debug("-----------------free get ctpl=" + JSON.toJSONString(ctpl));

            //免费领取模式
            try {
                if (zfuid == null) {
                    String guid = ori.split("_")[0];
                    User ruser = redisService.getUserByGuid(guid);
                    if (ruser != null) zfuid = ruser.getId();
                }
            } catch (Exception e) {
                logger.error("------------paifa zfuid parse error", e);
            }
            //免费领取模式
            couponshare.setQuanid(couponService.lingQuan("", zfuid, uid, ctpl, Qgettype.share));

            ctpl.setUse(ctpl.getUse() + 1);//已领取
            ctpl.setModifytime(new Date());
            ctpl.setModifier(uid);
            ctpl.updateById();

        } else if (ctpl.getZsmode().intValue() == 1) {
            //分享转增模式@0：分享领取(适合引流)；1：赠送领取(适合回流)
            // 判断是否被人领取
            if (coupon == null) {
                json.setCode(4);
                json.setMsg("该优惠券不存在");
                return json;
            }

            //赠送模式，转赠的优惠券不过期
            User quser = userService.selectOne(new EntityWrapper<User>()
                    .setSqlSelect("id,guid").eq("id", coupon.getUid()));

            if (quser == null || quser.getGuid() == null) {
                json.setCode(4);
                json.setMsg("该优惠券无效");
                return json;
            }

            if (ori.indexOf(quser.getGuid()) != 0) {
                json.setCode(1);
                json.setMsg("该优惠券已被人领取");
                return json;
            }

            coupon.setZfuid(coupon.getUid());
            coupon.setZfname(redisService.getUser(coupon.getUid()).getNickName());
            coupon.setUid(ObjectUtil.getUid());
            coupon.setOriginType(Qgettype.zengsong.getVal());
            coupon.setModifytime(new Date());
            coupon.setModifier(ObjectUtil.getUid());
            coupon.setAddress(store.getAddress());
            coupon.updateById();

            couponshare.setQuanid(coupon.getId());

            //更改旧的转发券记录
            CouponTplShare old = new CouponTplShare();
            old.setIszhuanfa(1);
            couponTplShareMapper.update(old, new EntityWrapper<CouponTplShare>().eq("quanid", coupon.getId()));
        } else {

        }

        couponshare.setTplid(tplid);
        couponshare.setCreatetime(new Date());

        couponshare.setCreateday(DateUtil.getToday());
        couponshare.setFenxiao(ctpl.getFenxiao());

        //xinhuiyuan 默认值
        //isused     默认值
        //领券动作不触发会员升级
        couponshare.setZfuid(zfuid);
        couponshare.setGetuid(uid);
        couponshare.setXinke(xkcout == 0 ? 1 : 0);
        couponshare.setSid(ctpl.getSid());

        couponshare.setLeagueid(ctpl.getLeagueid());
        couponshare.insert();

        Wrapper<CouponTplShare> shareEntity = new EntityWrapper<CouponTplShare>()
                .setSqlSelect("distinct getuid ")
                .eq("zfuid", zfuid).eq("tplid", tplid);
        if (ctpl.getXinke() == 1) shareEntity.eq("xinke", 1);

        List<CouponTplShare> couponTplShares = couponTplShareMapper.selectList(shareEntity);
        int sharecout = couponTplShares == null ? 0 : couponTplShares.size();

        //处理券分享逻辑
        //fenxiao:分销类型@0:无奖励(普通券)；1：普通分享奖励(推荐有礼)；2：裂变红包；3：分销奖励；
        // 0：普通分享奖励；
        // -1：否 无奖励
        logger.debug("-----------------couponRecevie ctpl.getFenxiao().intValue()=" + ctpl.getFenxiao().intValue());
        logger.debug("-----------------couponRecevie ctpl.getShareshu()=" + ctpl.getShareshu());
        logger.debug("-----------------couponRecevie sharecout=" + sharecout);

        if (ctpl.getEndtime() != null &&
                Long.parseLong(DateUtil.getToday().replaceAll("-", "")) >
                        Long.parseLong(ctpl.getEndtime().replaceAll("-", ""))) {
            //红包裂变券活动过期不奖励
            return json;
        }
        // 触发推荐有礼
        // 触发条件1>：分销模式为推荐有礼
        // 触发条件2>：在活动日期内
        // 触发条件3>：满足推荐条件分享多少人
        if (ctpl.getFenxiao().intValue() == Qfxtype.hongbao.getVal() && ctpl.getShareshu() != null &&
                sharecout % ctpl.getShareshu()==0) {
            // 触发裂变红包奖励
            AkkaServer.system.actorOf(Props.create(OrderActor.class))
                    .tell(Constants.AKKA_QUAN_SHARE_PAY + "@" + zfuid + "@" + tplid
                            + "@" + couponshare.getQuanid() + "@" + FantimeType.lingqu.getVal(), ActorRef.noSender());
        }

        // 触发推荐有礼
        logger.debug("-----------------couponRecevie ctpl.getFenxiao().intValue()=" + ctpl.getFenxiao().intValue());
        if (ctpl.getFenxiao().intValue() == Qfxtype.tuijian.getVal()) {

            String today = DateUtil.getToday().replace("-", "");
            Integer todaynum = Integer.parseInt(today);
            Boolean youli = true;
            if (!Strings.isNullOrEmpty(ctpl.getStarttime())) {
                String start = ctpl.getStarttime().replace("-", "");
                Integer startnum = Integer.parseInt(start);
                youli = todaynum >= startnum;
            }
            if (!Strings.isNullOrEmpty(ctpl.getEndtime())) {
                String end = ctpl.getEndtime().replace("-", "");
                Integer endnum = Integer.parseInt(end);
                youli = youli && todaynum <= endnum;
            }
            logger.debug("-----------------couponRecevie youli=" + youli);

            //只计数是往本店铺带新客
            Wrapper<CouponTplShare> sharesidEntity = new EntityWrapper<CouponTplShare>()
                    .setSqlSelect("id")
                    .eq("zfuid", zfuid)
                    .eq("tplid", tplid);

            int fxcout = couponTplShareMapper.selectCount(sharesidEntity);
            logger.debug("-----------------couponRecevie fxcout=" + fxcout);

            // 触发推荐有礼
            // 触发条件1>：分销模式为推荐有礼
            // 触发条件2>：在活动日期内
            // 触发条件3>：满足推荐条件分享多少人
            if (youli && ctpl.getFanid() != null && fxcout == ctpl.getShareshu()) {

                CouponTpl ctplli = couponTplService.selectById(ctpl.getFanid());
                if (ctplli != null) {
                    couponService.lingQuan("", null, zfuid, ctplli, Qgettype.tuijianli);
                }
            }
        }

        // =========待实现，领券不能自动升级，需要发展用户裂变会员
        // （部分行业支持领券新用户自动升级20200914 huakouyun）
        // 赠送券可以重复操作，重复赠送，接受赠送的人领到券也不代表回去发展会员
        // 触发会员升级
        boolean islbhuiyuan = false;
        CoupontplMember tocoupontplMember = null;

//        if (mpid == 11) {
//            List<CoupontplMember> cmembers = coupontplMemberMapper.selectList(new EntityWrapper<CoupontplMember>()
//                    .setSqlSelect("max(mlevel) mlevel")
//                    .eq("sid", ctpl.getSid()));
//            logger.debug("-----------------couponRecevie cmembers=" + JSON.toJSONString(cmembers));
//            logger.debug("-----------------couponRecevie cmembers.size=" + cmembers.size());
//            Integer maxlevel = cmembers.get(0) == null ? null : cmembers.get(0).getMlevel();
//
//            if (ctpl.getSid() != null && ctpl.getFenxiao().intValue() == Qfxtype.hyliebian.getVal()
//                    && maxlevel != null) {
//                islbhuiyuan = true;
//
//                //================处理转发者================
//                //只计数是往本店铺带新客
//                Wrapper<CouponTplShare> sharesidEntity = new EntityWrapper<CouponTplShare>()
//                        .setSqlSelect("distinct getuid ")
//                        .eq("zfuid", zfuid).eq("sid", ctpl.getSid()).eq("xinke", 1);
//
//                List<CouponTplShare> cptlshares = couponTplShareMapper.selectList(sharesidEntity);
//                int sidsharecout = cptlshares == null ? 0 : cptlshares.size();
//                int level = sidsharecout / 3;
//
//                level = level > maxlevel.intValue() ? maxlevel.intValue() : level;
//
//                CoupontplMember coupontplMemberentity = new CoupontplMember();
//                coupontplMemberentity.setSid(ctpl.getSid());
//                coupontplMemberentity.setMlevel(1);
//                tocoupontplMember = coupontplMemberMapper.selectOne(coupontplMemberentity);
//
//                //领取联盟会员之后默认是试用会员等级0，推荐3人升1级，推荐6人升2级，推荐9人升3级。。。
//                //比较当前会员等级
//                LeagueMember zfentity = new LeagueMember();
//                zfentity.setSid(ctpl.getSid());
//                zfentity.setUid(zfuid);
//                LeagueMember leagueMember = leagueMemberMapper.selectOne(zfentity);
//
//                //会员存在并且等级比level小
//                if (leagueMember != null && leagueMember.getMlevel() < level) {
//                    leagueMember.setMlevel(level);
//                    leagueMember.setModifytime(new Date());
//                    leagueMember.updateById();
//
//                    //每月15号固定发放券==待完善
//                    String today = DateUtil.getToday();
//                    int nowday = Integer.parseInt(today.substring(today.lastIndexOf("-") + 1));
//                    if (nowday >= 15) {
//                        cmembers = coupontplMemberMapper.selectList(new EntityWrapper<CoupontplMember>()
//                                .eq("mlevel", level)
//                                .eq("sid", ctpl.getSid()));
//                        for (CoupontplMember item : cmembers) {
//                            for (int i = 0; i < item.getNum(); i++) {
//                                couponService.lingQuan("", null, zfuid, couponTplService.selectById(item.getTplid()), Qgettype.huiyuan);
//                            }
//                        }
//                    }
//                }
//            }
//        }

        //================处理领取者================
        //========领券之后自动成为商家意向客户========
        //========领券之后自动为1级会员========
        if (ctpl.getSid() != null) {
            LeagueMember lmentity = new LeagueMember();
            lmentity.setUid(uid);
            lmentity.setSid(ctpl.getSid());
            LeagueMember leagueMember = leagueMemberMapper.selectOne(lmentity);

            if (leagueMember == null) {
                leagueMember = new LeagueMember();
                leagueMember.setUid(uid);
                leagueMember.setMid(ObjectUtil.getMid());
                leagueMember.setMpid(mpid);
                leagueMember.setShareid(zfuid);
                if (zfuid != null) leagueMember.setSharename(redisService.getUser(zfuid).getNickName());

                leagueMember.setCreatetime(new Date());
                leagueMember.setStartdate(new Date());
                leagueMember.setEnddate(DateUtil.addDay(new Date(), tocoupontplMember.getExpire()));
                leagueMember.setCreateday(DateUtil.getToday());
                leagueMember.setState(1);
                //领券之后默认为-1级，非会员，非联盟模式下为0，联盟模式下为-1
                //联盟模式-1非会员 0体验会员 1(1级会员)
                leagueMember.setMlevel(islbhuiyuan ? 1 : mpid == 11 ? 0 : -1);
                leagueMember.setUtype(Utype.youke.getVal());//默认0
                leagueMember.setCreator(uid);
                leagueMember.setLeagueid(ctpl.getLeagueid());
                leagueMember.setSid(ctpl.getSid());
                leagueMember.setSname(ctpl.getSname());

                leagueMember.setZhekou(ctpl.getCost());
                leagueMember.setZkname(ctpl.toNameString());
                leagueMember.setNickname(redisService.getUser().getNickName());
                leagueMember.setPhone(redisService.getUser().getPhone());
                leagueMember.setHeadimg(redisService.getUser().getAvatarPic());

                leagueMember.insert();
            }
        }

        //升级店铺体验会员，需要从联盟商家券哪里领取才能够升级，此处关闭
        //不管店铺是否开通会员裂变系统
//        if (ctpl.getMlevel() != null && ctpl.getMlevel().intValue() == 0
//                && ctpl.getSid() != null && ctpl.getSid().longValue() > 0 && ctpl.getLeagueid() != null) {
//            LeagueMember lmentity = new LeagueMember();
//            lmentity.setUid(uid);
//            lmentity.setSid(ctpl.getSid());
//            LeagueMember leagueMember = leagueMemberMapper.selectOne(lmentity);
//
//            if (leagueMember == null) {
//                leagueMember = new LeagueMember();
//                leagueMember.setUid(uid);
//                leagueMember.setMid(ObjectUtil.getMid());
//                leagueMember.setMpid(ObjectUtil.getMpid());
//                leagueMember.setShareid(zfuid);
//                if (zfuid != null) leagueMember.setSharename(redisService.getUser(zfuid).getNickName());
//
//                leagueMember.setCreatetime(new Date());
//                leagueMember.setStartdate(new Date());
//                leagueMember.setEnddate(DateUtil.addDay(new Date(), 30));
//                leagueMember.setState(1);
//                leagueMember.setMlevel(0);//领取联盟商圈默认0级：使用会员1个月，
//                leagueMember.setUtype(0);//默认0
//                leagueMember.setCreator(uid);
//                leagueMember.setLeagueid(ctpl.getLeagueid());
//                leagueMember.setSid(ctpl.getSid());
//                leagueMember.setSname(ctpl.getSname());
//
//                leagueMember.setZhekou(ctpl.getCost());
//                leagueMember.setZkname(ctpl.toNameString());
//                leagueMember.setNickname(redisService.getUser().getNickName());
//                leagueMember.setPhone(redisService.getUser().getPhone());
//                leagueMember.setHeadimg(redisService.getUser().getAvatarPic());
//
//                leagueMember.insert();
//            }
//        }

        return json;
    }

    @RequestMapping("/api/coupon/mytiyanka")
    @ResponseBody
    public Jinfo mytiyanka() {
        Jinfo jinfo = new Jinfo();

        List<Coupon> list = couponService.selectList(new EntityWrapper<Coupon>()
                .ge("type", 10).le("type", 16)
                .eq("uid", ObjectUtil.getUid())
                .eq("is_unused", 1)
                .eq("is_outdate", 0)
        );
        jinfo.setInfo(list);
        return jinfo;
    }

}
